package com.tengju.bff.interfaces.covercharge.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tengju.bff.interfaces.covercharge.constant.CoverChargeEnum;
import com.tengju.bff.interfaces.covercharge.constant.NoticeStatusEnum;
import com.tengju.bff.interfaces.covercharge.entity.dto.ServiceAuthInfoDTO;
import com.tengju.bff.interfaces.covercharge.entity.dto.ServiceContractDTO;
import com.tengju.bff.interfaces.covercharge.entity.po.ServiceContract;
import com.tengju.bff.interfaces.covercharge.entity.po.ServiceContractRelation;
import com.tengju.bff.interfaces.covercharge.entity.po.ServiceSign;
import com.tengju.bff.interfaces.covercharge.entity.vo.SelfCertificationQuery;
import com.tengju.bff.interfaces.covercharge.entity.vo.ServiceSignQuery;
import com.tengju.bff.interfaces.covercharge.mapper.ServiceContractMapper;
import com.tengju.bff.interfaces.covercharge.mapper.ServiceContractRelationMapper;
import com.tengju.bff.interfaces.covercharge.service.IMemberService;
import com.tengju.bff.interfaces.covercharge.service.IServiceSignService;
import com.tengju.bff.interfaces.covercharge.util.DateTimeUtils;
import com.tengju.bff.interfaces.covercharge.util.UserUtils;
import com.tengju.user.application.archives.StarSignService;
import com.tengju.user.domain.model.sign.StarAccountEvent;
import com.tengju.user.domain.model.sign.StarContractEvent;
import com.tengju.user.domain.model.user.UserIdCode;
import com.tengju.user.domain.shared.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.Objects;

/**
 * @author liang_shi
 * @date 2020/7/27 15:49
 * @description 会员服务
 */
@Slf4j
@Service
public class MemberAddStartServiceImpl implements IMemberService {


    @Autowired
    private ServiceContractRelationMapper contractRelationMapper;

    @Autowired
    private ServiceContractMapper contractMapper;

    @Autowired
    @Lazy
    private IServiceSignService serviceSignService;

    @Autowired
    StarSignService starSignService;


    /**
     * 会员模块-区域服务商签约成功入星接口
     *
     * @param contractId 合同Id
     */
    @Override
    public boolean dealMemberAddStart(String bizId, String contractId) {
        log.info("会员模块-区域服务商签约成功入星处理,业务流水号:{},contractId:{}", bizId, contractId);
        //默认处理成功
        try {
            ServiceContractRelation queryScr = new ServiceContractRelation();
            queryScr.setContractId(contractId);
            ServiceContractRelation scr = contractRelationMapper.selectOne(new QueryWrapper<>(queryScr));
            if (Objects.isNull(scr)) {
                log.error("会员模块-区域服务商签约成功入星处理,签署信息不存在,contractId:{}", contractId);
                return Boolean.FALSE;
            }
            ServiceContract querySc = new ServiceContract();
            querySc.setContractId(contractId);
            ServiceContract scInfo = contractMapper.selectOne(new QueryWrapper<>(querySc));
            if (Objects.isNull(scInfo)) {
                log.error("会员模块-区域服务商签约成功入星处理,合同信息不存在,contractId:{}", contractId);
                return Boolean.FALSE;
            }
            ServiceContractDTO contractDTO = new ServiceContractDTO();
            contractDTO.setBizId(scr.getBizId());
            contractDTO.setIdCode(scr.getIdCode());
            contractDTO.setPlatformCode(scr.getPlatformCode());
            contractDTO.setUserFrom(scr.getUserFrom());
            contractDTO.setContractId(contractId);
            log.info("会员模块-区域服务商签约成功入星处理,beginDate:{},,expireDate:{}", scInfo.getBeginDate(), scInfo.getExpireDate());
            String beginDate = DateTimeUtils.parseDateAsString(scInfo.getBeginDate(), DateTimeUtils.DEFAULT_DATE_TIME_FORMAT);
            String expireDate = DateTimeUtils.parseDateAsString(scInfo.getExpireDate(), DateTimeUtils.DATE_FORMAT);
            contractDTO.setBeginDate(beginDate);
            contractDTO.setExpireDate(expireDate);
            contractDTO.setType("JOIN_START");

            //入星
            StarContractEvent event = new StarContractEvent(
                    UserIdCode.of(contractDTO.getIdCode().longValue()),
                    contractId,
                    contractDTO.getUserFrom(),
                    DateUtil.dateToLocalDateTime(DateUtil.parseStringToDate(DateUtil.DATE_DAY_FORMAT, contractDTO.getBeginDate()))
            );
            starSignService.addStarData(event);
//            //发送MQ入星
//            sendAddStartMessage(contractDTO);
            return Boolean.FALSE;
        } catch (Exception e) {
            log.error("会员模块-区域服务商签约成功入星处理异常,业务流水号:{},contractId:{},异常信息:", bizId, contractId, e);
        }
        return Boolean.FALSE;
    }

    /**
     * 会员模块-认证通过生成待审批星级数据接口
     *
     * @param selfCertificationQuery 用户
     * @param auditTme               认证时间
     * @param beforeIdentity         上个身份
     * @param currentIdentity        当前身份
     */
    @Override
    public boolean dealMemberAddStarAudit(String bizId, SelfCertificationQuery selfCertificationQuery,
                                          Date auditTme, String beforeIdentity, String currentIdentity) {
        log.info("会员模块-区域服务商认证通过处理,业务流水号:{},selfCertification:{}", bizId, selfCertificationQuery);
        //星级区域服务商更新DT已经发送成功
        Integer userId = UserUtils.getUserId(selfCertificationQuery.getIdCode());
        try {
            this.updateSignNoticeStatus(userId, NoticeStatusEnum.NOTICE_NO.getCode(), NoticeStatusEnum.NOTICE_YES.getCode());

            //认证时间转为String
            String auditTmeStr = DateTimeUtils.parseDateAsString(auditTme, DateTimeUtils.DEFAULT_DATE_TIME_FORMAT);

            ServiceAuthInfoDTO authDTO = new ServiceAuthInfoDTO();
            authDTO.setBizId(bizId);
            authDTO.setIdCode(selfCertificationQuery.getIdCode());
            authDTO.setPlatformCode(selfCertificationQuery.getPlatformCode());
            authDTO.setAuditTme(auditTmeStr);
            authDTO.setBeforeIdentity(beforeIdentity);
            authDTO.setCurrentIdentity(currentIdentity);
            authDTO.setUserFrom(selfCertificationQuery.getType());
            authDTO.setType("AUTH");

            //入星
            StarAccountEvent event = new StarAccountEvent(
                    UserIdCode.of(authDTO.getIdCode().longValue()),
                    authDTO.getUserFrom(),
                    DateUtil.dateToLocalDateTime(DateUtil.parseStringToDate(DateUtil.DATE_TIME_FORMAT, authDTO.getAuditTme()))
            );
            starSignService.addAuditData(event);
//            //发送MQ入星
//            sendAddStartAuditMessage(authDTO);
            return Boolean.TRUE;
        } catch (Exception e) {
            log.info("会员模块-区域服务商认证通过处理失败,发送到MQ,bizId:{},userId:{}", bizId, userId);
            this.updateSignNoticeStatus(userId, NoticeStatusEnum.NOTICE_YES.getCode(), NoticeStatusEnum.NOTICE_NO.getCode());
        }
        return Boolean.FALSE;
    }

    /**
     * 修改签约记录
     *
     * @param userId             请求信息
     * @param searchNoticeStatus 搜索状态
     * @param noticeStatus       更新状态
     */
    private void updateSignNoticeStatus(Integer userId, Integer searchNoticeStatus, Integer noticeStatus) {
        ServiceSignQuery serviceSignInfo = serviceSignService.queryFirst(UserUtils.getIdCode(userId), CoverChargeEnum.ServiceAccountType.MANAGE_TYPE.getPlatform());
        if (serviceSignInfo != null && serviceSignInfo.getNoticeStatus().equals(searchNoticeStatus)) {
            ServiceSign serviceSign = new ServiceSign();
            serviceSign.setNoticeStatus(noticeStatus);
            serviceSign.setUpdatedTime(LocalDateTime.now().toString());
            serviceSign.setId(serviceSignInfo.getId());
            serviceSignService.updateById(serviceSign);
        }
    }
}
